package core.manager
{
	import flash.events.Event;
	import flash.events.IOErrorEvent;
	import flash.net.URLLoader;
	import flash.net.URLRequest;

	public class XMLManager
	{
		public function XMLManager()
		{
		}
		
		private static var _instance:XMLManager;
		
		public static function get instance():XMLManager {
			if(_instance == null){
				_instance = new XMLManager();
			}
			return _instance;
		}
		
		public function load():void {
			var urlLoader:URLLoader = new URLLoader();
			var path:String = "config.xml";
			var request:URLRequest = new URLRequest(path);
			urlLoader.addEventListener(Event.COMPLETE,onCompleted);
			urlLoader.addEventListener(IOErrorEvent.IO_ERROR,onError);
			urlLoader.load(request);
		}
		
		private var _xml:XML;
		
		private function onCompleted(event:Event):void {
			var urlLoader:URLLoader = event.target as URLLoader;
			urlLoader.removeEventListener(Event.COMPLETE,onCompleted);
			urlLoader.removeEventListener(IOErrorEvent.IO_ERROR,onError);
			this._xml = XML(urlLoader.data);
			
			var items:Array = this.getItems("items");
			SpriteSheetManager.instance.items = items;;
		}
		
		private function getObject(v:*):Object {
			var object:Object = {};
			var attNamesList:XMLList = v.@*;
			for(var i:int = 0; i < attNamesList.length(); i++){
				var childName:String = attNamesList[i].name();
				var childValue:* = v.attribute(childName).toString();
				object[childName] = childValue;
			}
			return object;
		}
		
		private function getItems(key:String):Array {
			var config:XMLList = this._xml.config;
			var result:Array = [];
			for each(var v:XML in config.children()){
				if(v.localName() == key){
					for each(var t:* in v.children()){
						result.push(this.getObject(t));
					}
				}
			}
			return result;
		}
		
		private function onError(event:Event):void {
			
		}
	}
}